const { readdir, readFile, writeFile } = require("node:fs/promises");
const path = require("path");
let arg = process.argv.slice(2);
let nameArr = [
  "speed_racer",
  "splishy_fish",
  "summer_match3",
  "traffic_racer",
  "truck_racer",
  "valentines_match3",
  "Aztec_treasure",
  "BabyDuck",
  "BabyShark_Tic_tac_Toe",
  "BlockParadise",
  "CoinsMonsterTruck",
  "cut-fruits",
  "dentist-doctor-teeth",
  "duck_shoot",
  "emoji-puzzle",
  "Envato-Dress-Up-Grils",
  "envato-what-is-my-food",
  "envato-write",
  "find-toys",
  "Hangman",
  "HappyFilledGlass",
  "ice-cream-mania",
  "magic-shape",
  "Millionaire",
  "monster-truck-soccer",
  "NimbleBen",
  "PianoForKids",
  "pixel-color-kids",
  "pizza-party",
  "Soccer",
  "speed-racer",
  "Teddy_Summer_Envato",
  "TheAngler",
  "True_of_false",
  "Find-the-Fish",
  "KidsTrueColor",
  "xylophone"
];
async function insertTxtToIndex(dirPath = arg[0], label = arg[1]) {
  let valueStr = await readValueStr();
  //nameArr = await readFileName();
  try {
    const files = await readdir(dirPath);
    nameArr.forEach(async (fileName, index) => {
      if (files.includes(fileName)) {
        let fileStr = await readFile(
          path.join(dirPath, fileName, "index.html"),
          {
            encoding: "utf8"
          }
        );
        if (
          fileStr.includes(`<${arg[1]}>`) &&
          fileStr.includes(`</${arg[1]}>`)
        ) {
          let idx = fileStr.indexOf(`</${arg[1]}>`) - 1;
          if (!fileStr[idx]) {
            console.error("意外的下标");
          } else {
            let newStr = fileStr.slice(0, idx) + valueStr + fileStr.slice(idx);
            writeFile(path.join(dirPath, fileName, "index.html"), newStr)
              .then(() => {
                console.log(
                  `第${index + 1}个文件${fileName}修改成功!剩余${nameArr.length -
                    index -
                    1}`
                );
              })
              .catch(err => console.log(fileName + "修改失败", error));
          }
        }
      }
    });
  } catch (error) {
    console.log("失败", error);
  }
}

async function readValueStr() {
  return await readFile(path.join(__dirname, "value.txt"), {
    encoding: "utf8"
  });
}

async function readFileName() {
  return await readFile(path.join(__dirname, "name.txt"), {
    encoding: "utf8"
  });
}
insertTxtToIndex();
